package com.photons.timesync.socket

import com.photons.timesync.Constants
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.lang.Exception
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import javax.inject.Inject

class UDPSocket @Inject constructor() {
    private val socket: DatagramSocket = DatagramSocket(Constants.PORT)
    private val receiveBuffer = ByteArray(Constants.BUFFER_LENGTH)

    init {
        socket.soTimeout = 500
    }

    suspend fun sendMessageWithReply(
        message: ByteArray,
        addr: String?,
        port: Int
    ): DatagramPacket? {
        return withContext(Dispatchers.IO) {
            try {
                val target = InetAddress.getByName(addr)
                val packet = DatagramPacket(message, message.size, target, port)
                val replyPacket = DatagramPacket(receiveBuffer, Constants.BUFFER_LENGTH)
                socket.send(packet)
                socket.receive(replyPacket)

                replyPacket
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }
    }
}